<template>
  <div
    v-loading="pageLoading"
    element-loading-background="rgba(255, 255, 255, 0.6)"
    class="detail-wrap"
  >
    <div class="top-content">
      <el-button size="mini" @click="handleRefresh" type="primary"
        >刷新进度</el-button
      >
      <el-button size="mini" type="primary" @click="handleGoBack"
        >返回</el-button
      >
    </div>
    <el-card class="card flow-card">
      <div class="flow-wrap">
        <div class="item-wrap">
          <img
            :src="
              isAssociatedState
                ? imgUrlObj.associated
                : imgUrlObj.associatedGrey
            "
          />
          <el-button
            v-if="!isDataCheckState"
            :disabled="!isAssociatedBtnState"
            size="medium"
            type="text"
            @click="handleAssociatedGoods('init')"
            >关联商品</el-button
          >
          <el-button
            v-else
            :disabled="!isAssociatedBtnState"
            size="medium"
            type="text"
            @click="handleAssociatedGoods('repeat')"
            >重新关联</el-button
          >
          <el-button
            v-if="!isDataCheckState"
            :disabled="!isAssociatedBtnState"
            style="margin-left: 0"
            size="medium"
            type="text"
            @click="handleSeniorLinked"
            >高级关联</el-button
          >
          <el-row
            v-if="isShowSeniorTips"
            class="senior_linked_wrap"
            type="flex"
            align="middle"
          >
            <span>生成数据中...请手动刷新查看进度</span>
            <el-button
              size="medium"
              type="text"
              icon="el-icon-refresh"
              @click="handleRefresh"
              ></el-button>
          </el-row>
        </div>
        <div :class="[isExportState ? 'line-blue' : 'line-grey']"></div>
        <div class="item-wrap">
          <img :src="isExportState ? imgUrlObj.export : imgUrlObj.exportGrey" />
          <el-button
            :disabled="!isExportBtnState"
            size="medium"
            type="text"
            @click="handleExportTemplate"
            >导出模板</el-button
          >
        </div>
        <div :class="[isImportState ? 'line-blue' : 'line-grey']"></div>
        <div class="item-wrap">
          <img :src="isImportState ? imgUrlObj.import : imgUrlObj.importGrey" />
          <el-upload
            v-if="!isDataCheckState"
            class="upload-temp"
            ref="bacthUpload"
            :action="`${uploadBaseURL}dataBatch/purchasePrice/file/upload/templateData/${batchNo}`"
            accept=".xls, .xlsx"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :data="{ batchNo }"
            :disabled="!isImportBtnState"
          >
            <el-button
              :disabled="!isImportBtnState"
              slot="trigger"
              size="medium"
              type="text"
              >导入模板</el-button
            >
          </el-upload>
          <el-button
            v-if="isDataCheckState"
            :disabled="!isImportBtnState"
            size="medium"
            type="text"
            @click="handleReimport"
            >重新导入</el-button
          >
          <el-button
            class="import-record-btn"
            v-if="isDataCheckState"
            :disabled="!isImportBtnState"
            size="medium"
            type="text"
            @click="handleViewRecord"
            >导入记录</el-button
          >
        </div>
        <div :class="[isDataCheckState ? 'line-blue' : 'line-grey']"></div>
        <div class="item-wrap">
          <img :src="isDataCheckState ? imgUrlObj.dataCheck : imgUrlObj.dataCheckGrey" />
          <el-button
            :disabled="!isDataCheckBtnState"
            size="medium"
            type="text"
            >{{ isDataCheckBtnState ? "数据校验中" : "数据校验" }}</el-button
          >
        </div>
        <template v-if="canOpeState">
          <div :class="[isSubmmitState ? 'line-blue' : 'line-grey']"></div>
          <div class="item-wrap">
            <img
              :src="isSubmmitState ? imgUrlObj.submit : imgUrlObj.submitGrey"
            />
            <el-button
              :disabled="!isSubmmitBtnState"
              size="medium"
              type="text"
              @click="handleSubmitAudit"
              >提交审核</el-button
            >
          </div>
        </template>
      </div>
    </el-card>
    <el-card class="card form-card">
      <div class="left-wrap">
        <div class="item">
          <span class="title">已关联行数</span>
          <span class="account">({{ detailObj.exportCount }})</span>
        </div>
        <div v-if="detailObj.exportErrorCount" class="item">
          <span class="title">关联失败行数</span>
          <el-popover
            class="account"
            placement="top-start"
            width="200"
            trigger="hover"
            :content="detailObj.exportErrorReason">
            <span slot="reference" class="account">({{ detailObj.exportErrorCount }})</span>
          </el-popover>
        </div>
        <div class="item">
          <span class="title">已导入行数</span>
          <span class="account">({{ detailObj.importCount }})</span>
        </div>
        <div class="item">
          <span class="title">校验成功行数</span>
          <span class="account">({{ detailObj.validSuccessCount }})</span>
        </div>
        <div class="item">
          <span class="title">校验异常行数</span>
          <span class="account">({{ detailObj.validErrorCount }})</span>
        </div>
        <div class="btn-wrap">
          <el-button type="text" :disabled="!detailObj.validSuccessCount" @click="handleExportNormalData"
            >导出正常数据(审核)</el-button
          >
          <el-button type="text" :disabled="!detailObj.validErrorCount" @click="handleExportAbnormalData"
            >导出异常数据</el-button
          >
          <el-upload
            class="upload-temp"
            ref="bacthUpload"
            :action="`${uploadBaseURL}dataBatch/purchasePrice/file/upload/validErrorData/${batchNo}`"
            accept=".xls, .xlsx"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :data="{ batchNo }"
            :disabled="!detailObj.validErrorCount"
          >
            <el-button :disabled="!detailObj.validErrorCount" slot="trigger" type="text">导入异常数据</el-button>
          </el-upload>
        </div>
      </div>
      <div class="right-wrap">
        <el-form
          ref="submitForm"
          :model="submitForm"
          :rules="formValidate"
          label-width="140px"
        >
          <el-form-item label="发起标题:" prop="title">
            <el-input
              show-word-limit
              maxlength="30"
              v-model.trim="submitForm.title"
              placeholder="建议填写厂家名称+调价原因，方便后续查询"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否自动调整售价:" prop="autoModifySaleprice">
            <el-select v-model="submitForm.autoModifySaleprice" placeholder="请选择">
              <el-option
                v-for="item in autoModifySalepriceOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述:" prop="reason" :rules="reasonRequired ? formValidate.reason : [{ required: false }]">
            <el-input
              type="textarea"
              show-word-limit
              maxlength="200"
              :rows="5"
              v-model.trim="submitForm.reason"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="end">
              <el-button size="mini" type="primary" @click="handleSaveInitInfo"
                >保存</el-button
              >
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="card info-card">
      <el-row>
        <span class="item"
          >单据号：<span>{{ batchNo || detailObj.batchNo }}</span></span
        >
        <span class="item"
          >单据状态：<span>{{ detailObj.batchStatusName }}</span></span
        >
        <span class="item"
          >制单人：<span>{{ detailObj.createdUserName }}</span></span
        >
        <span class="item"
          >制单时间：<span>{{ detailObj.createdAt }}</span></span
        >
        <span class="item"
          >提交人：<span>{{ detailObj.submitUserName }}</span></span
        >
        <span class="item"
          >提交时间：<span>{{ detailObj.submitAt }}</span></span
        >
        <span class="item"
          >所属部门：<span>{{ detailObj.departmentName }}</span></span
        >
        <span class="item"
          >所属区域：<span>{{ detailObj.areaName }}</span></span
        >
        <span v-if="batchState == 90" class="item"
          >审批驳回原因：<span>{{ detailObj.rejectReason }}</span></span
        >
      </el-row>
    </el-card>
    <associated-dialog
      :visible.sync="dialogVisible"
      :batchNo="batchNo"
      @hideDialog="handleHideDialog"
    />
    <record-dialog
      ref="record"
      :visible.sync="recordDialogVisible"
      :batchNo="batchNo"
      @hide-dialog="handleHideRecordDialog"
    />
    <el-dialog
      class="reimport-dialog"
      :top="'40vh'"
      title="提示"
      :visible.sync="reimportDialogVisible"
      width="32%"
    >
      <span>重新导入需停止数据校验并清空历史所有导入数据,是否继续？</span>
      <span slot="footer" class="dialog-footer">
        <el-button
          class="cancel-btn"
          size="mini"
          @click="reimportDialogVisible = false"
          >取消</el-button
        >
        <el-upload
          class="upload-temp"
          ref="bacthUpload"
          :action="`${uploadBaseURL}dataBatch/purchasePrice/file/upload/templateData/${batchNo}?reImport=1`"
          accept=".xls, .xlsx"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :data="{ batchNo }"
        >
          <el-button
            slot="trigger"
            type="primary"
            size="mini"
            @click="reimportDialogVisible = false"
            >确定</el-button
          >
        </el-upload>
      </span>
    </el-dialog>
    <!-- 高级关联 - 上架弹框 -->
    <SeniorLinkedDialog
      :okText="seniorLinked.okText"
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="submitSeniorLinkedResults"
    />
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { isResponseSuccess, setAuthBtnId } from '@/utils/bizUtils';
import AssociatedDialog from './components/AssociatedGoodDialog';
import RecordDialog from './components/ImportRecordDialog.vue';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import { requestToStatus } from '@/api/commonHttp';
import { getCanOpeState } from '@/utils/getUtils';

export default {
  name: 'Detail',
  components: {
    AssociatedDialog,
    RecordDialog,
    SeniorLinkedDialog
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      pageLoading: false,
      // 关联商品弹框
      dialogVisible: false,
      // 重新导入弹框显影
      reimportDialogVisible: false,
      isSaved: '',
      batchNo: '',
      pageType: '',
      batchState: 0,
      imgUrlObj: {
        associated: require('@/assets/images/finance/associated.png'),
        associatedGrey: require('@/assets/images/finance/associated-grey.png'),
        export: require('@/assets/images/finance/export.png'),
        exportGrey: require('@/assets/images/finance/export-grey.png'),
        import: require('@/assets/images/finance/import.png'),
        importGrey: require('@/assets/images/finance/import-grey.png'),
        dataCheck: require('@/assets/images/finance/data-check.png'),
        dataCheckGrey: require('@/assets/images/finance/data-check-grey.png'),
        submit: require('@/assets/images/finance/submit.png'),
        submitGrey: require('@/assets/images/finance/submit-grey.png')
      },
      submitForm: {
        title: '',
        reason: '',
        autoModifySaleprice: '',
      },
      formValidate: {
        title: [
          { required: true, message: '发起标题不能为空', trigger: 'blur' }
        ],
        autoModifySaleprice: [
          { required: true, message: '请选择是否自动调整售价', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请填写不自动调价原因', trigger: 'blur' }
        ]
      },
      detailObj: {
        batchNo: '',
        batchStatusName: '',
        createdUserName: '',
        createdAt: '',
        submitUserName: '',
        submitAt: '',
        departmentName: '',
        areaName: '',
        exportCount: 0,
        exportErrorCount: 0,
        exportErrorReason: '',
        importCount: 0,
        validSuccessCount: 0,
        validErrorCount: 0,
        rejectReason: ''
      },
      recordDialogVisible: false,
      autoModifySalepriceOption: [
        { label: '是', value: 1 },
        { label: '否', value: 2 }
      ],
      seniorLinked: {
        visible: false,
        okText: '提交',
        columns: [
          { label: '供应商编码', prop: 'supplyUuid', type: 'textarea' },
          { label: 'SKU编码', prop: 'skuNo', type: 'textarea' }
        ],
        dataSource: [{ supplyUuid: '', skuNo: '' }]
      },
      linkState: false, // 关联状态，当关联商品或高级关联提交成功后为true
    };
  },
  computed: {
    // 任务状态： 0:待关联商品 10待导出 20导出中 30待导入 35重新导入 40导入中 50待校验 55 校验中 60待提交 59 重新校验并提交待审核 70 待审核 80 审核成功 90 审核驳回
    // 重新关联图标高亮状态
    isAssociatedState () {
      return [0, 10, 20, 30, 35, 40, 50, 55, 59, 60, 70, 80, 90].includes(
        this.batchState
      );
    },
    // 导出模板图标高亮状态
    isExportState () {
      return [20, 30, 35, 40, 50, 55, 59, 60, 70, 80, 90].includes(this.batchState);
    },
    // 导入模板、重新导入图标高亮状态
    isImportState () {
      return [30, 35, 40, 50, 55, 59, 60, 70, 80, 90].includes(this.batchState);
    },
    // 数据校验图标高亮状态
    isDataCheckState () {
      return [35, 50, 55, 59, 60, 70, 80, 90].includes(this.batchState);
    },
    // 提交审核图标高亮状态
    isSubmmitState () {
      return [60, 70, 80, 90].includes(this.batchState);
    },
    // 按钮状态
    // 关联商品按钮状态
    isAssociatedBtnState () {
      return [0, 10, 20, 30, 60, 90].includes(this.batchState);
    },
    // 导出模板按钮状态
    isExportBtnState () {
      return [20, 30, 60, 90].includes(this.batchState);
    },
    // 导入模板按钮状态
    isImportBtnState () {
      return [30, 60, 90].includes(this.batchState);
    },
    // 数据校验按钮高亮状态
    isDataCheckBtnState () {
      return [50, 55, 59].includes(this.batchState);
    },
    // 提交按钮状态
    isSubmmitBtnState () {
      return [60, 90].includes(this.batchState);
    },
    // 描述必填
    reasonRequired () {
      return this.submitForm.autoModifySaleprice == 2;
    },
    // 展示高级关联提示
    isShowSeniorTips () {
      return this.linkState && this.batchState < 20;
    }
  },
  watch: {},
  created () {
    this.setCanOpeState()
    const { batchNo, type } = this.$route.query;
    this.batchNo = batchNo;
    this.pageType = type;
  },
  mounted () {
    if (this.pageType != 'add') {
      this.getDetailService();
    }
  },
  methods: {
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // 重新关联删除已关联数据
    deleteBatchDataService () {
      this.switchLoadingState(true);
      ApiRequest(`/dataBatch/purchasePrice/remove/${this.batchNo}`, 'post', {})
        .then((res) => {
          this.switchLoadingState(false);
          if (isResponseSuccess(res)) {
            this.dialogVisible = true;
          }
        })
        .catch(() => {
          this.switchLoadingState(false);
        });
    },
    // 获取详情
    getDetailService (isReLoad) {
      this.switchLoadingState(true);
      ApiRequest(`/dataBatch/purchasePrice/info/${this.batchNo}`, 'get', {})
        .then((res) => {
          this.switchLoadingState(false);
          if (isResponseSuccess(res) && res.retData) {
            this.detailObj = res.retData;
            const { batchStatus = 0, title = '', reason = '', autoModifySaleprice } = res.retData;
            this.batchState = batchStatus || 0;
            this.isSaved = title;
            this.submitForm = {
              title,
              reason,
              autoModifySaleprice
            };
            if (!isReLoad) this.linkState = true;
            if (isReLoad) {
              this.$message.success('刷新进度成功');
            }
          }
        })
        .catch(() => {
          this.switchLoadingState(false);
        });
    },
    // 提交审核
    submitService (param) {
      this.switchLoadingState(true);
      ApiRequest(`/dataBatch/purchasePrice/modify`, 'post', param)
        .then((res) => {
          this.switchLoadingState(false);
          if (isResponseSuccess(res)) {
            this.$message.success('提交成功')
            this.handleGoBack()
          }
        })
        .catch(() => {
          this.switchLoadingState(false);
        });
    },
    // 保存发起标题、原因信息
    saveInitInfoService (param, isSubmit) {
      if (param.autoModifySaleprice == 2 && !param.reason) {
        return this.$message.warning('请在描述里填写不自动调价原因');
      }
      this.switchLoadingState(true);
      ApiRequest(`/dataBatch/purchasePrice/modify/title`, 'post', param)
        .then((res) => {
          this.switchLoadingState(false);
          if (isResponseSuccess(res)) {
            this.$message.success(res.retMessage);
            this.getDetailService();
            if (isSubmit && res.retMessageKey != 1) {
              this.handleSubmit();
            }
          }
        })
        .catch(() => {
          this.switchLoadingState(false);
        });
    },
    // 导出文件
    exportFileService (type) {
      this.switchLoadingState(true);
      ApiRequest(
        `/dataBatch/purchasePrice/file/downloadUrl/${type}/${this.batchNo}`,
        'get',
        {}
      )
        .then((res) => {
          this.switchLoadingState(false);
          if (isResponseSuccess(res)) {
            if (res.retData && res.retData.downloadUrl) {
              window.location.href = res.retData.downloadUrl;
              this.getDetailService();
            }
          }
        })
        .catch(() => {
          this.switchLoadingState(false);
        });
    },
    // 刷新进度
    handleRefresh () {
      this.getDetailService(true);
    },
    // 刷新进度
    handleGoBack () {
      this.$router.go(-1);
    },
    // 关闭关联商品弹框
    handleHideDialog (state) {
      this.dialogVisible = false;
      // 判断是否有关联操作
      if (state) {
        this.getDetailService();
      }
    },
    // 提交审核
    handleSubmit () {
      this.$refs.submitForm.validate((valid) => {
        if (valid) {
          const param = {
            batchStatus: 70,
            batchNo: this.batchNo,
          };
          this.submitService(param);
        }
      });
    },
    // 关联商品
    handleAssociatedGoods (type) {
      if (type == 'init') {
        this.dialogVisible = true;
      } else {
        this.$confirm('重新关联将会清空已关联商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
          // type: 'warning'
        })
          .then(() => {
            this.deleteBatchDataService()
          })
          .catch(() => {});
      }
    },
    // 导入数据前校验
    handleBeforeUpload (res) {
      /* const canUpload = !!this.isSaved
      if (!canUpload) {
        this.$message.warning('请先保存是否自动调整售价信息，导入模板后将禁止修改')
      } else {
        this.switchLoadingState(true);
      }
      return canUpload; */
      this.switchLoadingState(true);
    },
    // 导入数据成功回调
    handleUploadSuccess (res) {
      if (isResponseSuccess(res)) {
        this.$message.success('导入模板成功');
        this.getDetailService();
      } else {
        this.$message.error(res.retMessage || '导入异常');
      }
      this.switchLoadingState(false);
    },
    // 导入数据失败回调
    handleUploadError (res) {
      this.switchLoadingState(false);
      this.$message.error(res.error || '导入失败');
    },
    // 保存发起标题和原因
    handleSaveInitInfo () {
      this.$refs.submitForm.validate((valid) => {
        if (valid) {
          const param = {
            batchNo: this.batchNo,
            ...this.submitForm
          };
          this.saveInitInfoService(param);
        }
      });
    },
    // 提交审核
    handleSubmitAudit () {
      this.$refs.submitForm.validate((valid) => {
        if (valid) {
          const param = {
            batchNo: this.batchNo,
            ...this.submitForm
          };
          this.saveInitInfoService(param, true);
        }
      });
    },
    // 导出模板
    handleExportTemplate () {
      this.exportFileService('outputTemplateData');
    },
    // 导出正常数据
    handleExportNormalData () {
      this.exportFileService('outputOutputData');
    },
    // 导出异常数据
    handleExportAbnormalData () {
      this.exportFileService('outputValidErrorData');
    },
    // 页面loading状态控制
    switchLoadingState (state) {
      this.pageLoading = state;
    },
    // 重新导入
    handleReimport () {
      this.reimportDialogVisible = true;
    },
    // 关闭导入记录弹框
    handleHideRecordDialog () {
      this.recordDialogVisible = false;
    },
    // 查看导入记录
    handleViewRecord () {
      this.recordDialogVisible = true;
      this.$refs.record.handleGetRecord(1)
    },
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true;
    },
    // 提交高级关联结果
    async submitSeniorLinkedResults (highRankingRelParam) {
      setAuthBtnId('高级关联');
      const data = {
        highRankingRelParam,
        batchNo: this.batchNo,
        submitType: 3
      }
      const retStatus = await requestToStatus({
        url: '/dataBatch/purchasePrice/submitParams',
        type: 'post',
        data,
        loadingFn: state => { this.switchLoadingState(state); }
      });
      if (retStatus) {
        this.$message.success('提交成功');
        this.linkState = true;
        this.handleRefresh();
      }
    }
  }
};
</script>
<style lang="less" scoped>
.top-content {
  float: right;
  margin-bottom: 10px;
}
.detail-wrap {
  .card {
    margin-bottom: 20px;
  }
  .flow-card {
    width: 100%;
    .flow-wrap {
      display: flex;
      justify-content: center;
      padding: 20px 0 0 0;
      img {
        margin: 5px auto;
        display: block;
      }
      .text {
        font-size: 14px;
        color: #666;
        line-height: 22px;
        font-weight: 400;
      }
      .item-wrap {
        width: 70px;
        text-align: center;
      }
      .line-grey {
        width: 19%;
        height: 2px;
        background: #d7d7d7;
        border-radius: 1px;
        margin-top: 32px;
      }
      .line-blue {
        width: 19%;
        height: 2px;
        background: #2898ed;
        border-radius: 1px;
        margin-top: 32px;
      }
      .import-record-btn {
        margin-left: 0px;
        margin-top: -8px;
      }
    }
  }
  .form-card {
    font-size: 14px;
    line-height: 22px;
    font-weight: 400;
    .left-wrap {
      float: left;
      color: #666;
      width: 50%;
      border-right: 1px dashed #dadada;
      padding-right: 20px;
      .item {
        border-bottom: 1px solid #eee;
        padding: 10px;
        .account {
          color: #d0021b;
          float: right;
        }
      }
      .btn-wrap {
        margin: 20px 0;
        button {
          margin-right: 10px;
        }
      }
    }
    .right-wrap {
      width: 49%;
      float: right;
      /deep/.el-select {
        width: 100%;
      }
    }
  }
  .info-card {
    font-size: 14px;
    color: #666;
    font-weight: 400;
    .item {
      margin-right: 30px;
    }
  }
  .upload-temp {
    display: inline;
  }
  .reimport-dialog {
    /deep/.el-dialog__body {
      padding: 10px 20px;
    }
    .cancel-btn {
      margin-right: 10px;
    }
  }
}

.senior_linked_wrap {
  span {
    margin-left: 6px;
    color: #FF4040;
    white-space: nowrap;
  }
}
</style>
